# -*- coding: utf-8 -*-

###############################################################################
# Copyright [2010] [Roberto Carrasco - rcarrasco@talentus.cl]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License. 
###############################################################################

"""A simple thread safe byte circular queue."""

import threading

class SimpleByteQueue:
    def __init__(self, queue_size):
        self.mutex = threading.Lock()
        self.size = queue_size + 1
        self.data = bytearray(self.size)
        self.start = 0
        self.end = 0

    def append(self, c):
        self.mutex.acquire()
        retval = False
        if (self.end + 1) % self.size!=self.start:
            self.data[self.end] = c
            self.end = (self.end + 1)%self.size
            retval = True
        self.mutex.release()
        return retval

    def pop(self):
        self.mutex.acquire()
        retval = -1
        if self.start != self.end :
            c = self.data[self.start]
            self.start= (self.start + 1)%self.size
            retval = c
        self.mutex.release()
        return retval

    def empty(self):
        self.mutex.acquire()
        self.start = 0
        self.end = 0
        self.mutex.release()

    def is_empty(self):
        self.mutex.acquire()
        e = (self.start == self.end)
        self.mutex.release()
        return e
